<template>
  <div class="product">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="商品标题" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type1" placeholder="商品类型" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type2" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <!--<el-select v-model="listQuery" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        查找
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        发布
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox>
    </div>

    <div>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        增加
      </el-button>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageCount"
      @pagination="getList"
    />

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="id" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="商品名称"
        prop="title"
        sortable="custom"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="商品图片"
        prop="pic"
        sortable="custom"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <img width="80" :src="scope.row.pic">
        </template>
      </el-table-column>
      <el-table-column
        label="商品价格"
        prop="price"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="销量"
        prop="count"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.buyCount }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上架时间"
        prop="create_date"
        sortable="custom"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createDate }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="分类1"
        prop="type1"
        sortable="custom"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.type1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="分类2"
        prop="type2"
        sortable="custom"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.type2 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="所属商家"
        prop="merchent"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.merchant.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDel(row)">
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="商品价格" prop="compnay" type="number">
          <el-input v-model="temp.price" />
        </el-form-item>
        <el-form-item label="商品分类1" prop="tel">
          <el-select v-model="listQuery.type1" placeholder="商品类型" clearable style="width: 90px" class="filter-item">
            <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类2" prop="pwd">
          <el-select v-model="listQuery.type2" placeholder="Type" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in calendarTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片网址" prop="pic">
          <vue-ueditor-wrap
            v-model="temp.pic"
            :config="myConfig"
          />
        </el-form-item>
        <el-form-item label="商品所属商家" prop="pwd">
          <el-input v-model="temp.mer_id" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import ajax from '@/utils/baseurl'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import VueUeditorWrap from 'vue-ueditor-wrap'

var p
export default {
  name: 'Product',
  components: { Pagination, VueUeditorWrap },
  directives: { waves },
  data() {
    return {
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 140,
        // 初始容量宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址我为了方便各位体验文件上传）
        serverUrl: 'http://localhost:8080/upload',
        UEDITOR_HOME_URL: '/Ueditor/'
      },
      temp: {
        title: '',
        pic: '',
        buyCount: 0,
        createDate: '',
        count: 0,
        price: 0,
        id: 0,
        type1: '',
        type2: '',
        mer_id: 0
      },
      rules: {
        title: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        pic: [{ required: true, message: '价格不能为空', trigger: 'change' }
        ],
        type1: [{ required: true, message: '类型不能为空', trigger: 'change' }],
        price: [{ required: true, message: '价格不能为空', trigger: 'change' }]

      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      listQuery: {
        title: '',
        type2: '',
        type1: '',
        pageCount: 10,
        pageNum: 1,
        sort: '+id'
      },
      total: 0,
      tableKey: 0,
      listLoading: true,
      list: null,
      importanceOptions: ['按件洗', '热门推荐', '精品推荐', '按打包价洗护', '快速洗', '奢护洗', '鞋类洗', '家纺洗'],
      calendarTypeOptions: [
        '正常',
        '售罄',
        '特价'
      ],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false
    }
  },
  created() {
    p = this
    // console.log(ajax);
    this.getList()
  },
  methods: {
    handleFilter() {
    },
    updateData() {
      this.updateData()
    },
    resetTemp() {
      this.temp = {
        title: '',
        pic: '',
        price: '',
        type1: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          ajax('addProduct'
            , this.temp, function(data) {
              if (data) {
                p.dialogFormVisible = false
                p.getList()
                p.$notify({
                  title: '完成',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
        }
      })
    },
    updateData() {
      console.log(p.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          ajax('updateProduct'
            , this.temp, function(data) {
              if (data) {
                p.dialogFormVisible = false
                p.getList()
                p.$notify({
                  title: '完成',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
        }
      })
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    handleDel(row) {
      var p = this
      this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ajax('delProductById', { id: row.id }, function(data) {
          if (data) {
            p.getList()
            p.$message({
              type: 'success',
              message: '删除成功!'

            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getList() {
      this.listLoading = true

      ajax('getAllProduct', p.listQuery, function(data) {
        console.log(data)
        console.log(p.listQuery)
        p.list = data.page.list
        p.total = data.page.totalCount
        p.listLoading = false
      })
    }

  }
}
</script>

